#include <iostream>
#include <signal.h>

#include "../comm/httplib.h"
#include "oj_control.hpp"

using namespace httplib;
using namespace ns_control;

static Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    ctrl_ptr->RecoveryMachine();
}

int main()
{
    signal(SIGQUIT, Recovery);

    Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;

    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
            {
                // 返回一个包含所有题目的网页
                std::string html;
                ctrl.GetAllQuestion(&html); 
                resp.set_content(html,"text/html;charset=utf-8"); });

    // /question/100 -> 正则匹配
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp)
            {
                std::string html; 
                std::string number=req.matches[1];
                ctrl.Question(number,&html); 
                resp.set_content(html,"text/html;charset=utf-8"); });

    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
             {
                std::string number=req.matches[1];
                std::string result_json;
                ctrl.Judge(number,req.body,&result_json);
                resp.set_content(result_json,"application/json;charset=utf-8"); });
    // resp.set_content("这是第"+number+"道题的判题","text/plain;charset=utf-8"); });

    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8899);
    return 0;
}